package fr.xebia.monitoring.appender;

import java.io.IOException;
import java.io.Writer;

import fr.xebia.monitoring.beans.AggregatedMeasures;
import fr.xebia.monitoring.beans.Measure;
import fr.xebia.monitoring.config.MeasureType;

public class ConsoleAppender extends AbstractMeasureAppender {

	@Override
	public void run() {
		if (getMeasureType().equals(MeasureType.AGGREGATED)) {
			logger.debug("Appending aggregated measures");
			AggregatedMeasures agregatedMeasures = getAggregatedMeasures();
			getFormater().format(agregatedMeasures, new SystemOutWriter());
		} else {
			logger.debug("Appending raw measures");
			Measure[] measures = getMeasures();
			getFormater().format(measures, new SystemOutWriter());
		}
	}
	
	private class SystemOutWriter extends Writer {

		@Override
		public void write(char[] cbuf, int off, int len) throws IOException {
			System.out.write(String.valueOf(cbuf, off, len).getBytes());
		}

		@Override
		public void flush() throws IOException {
			System.out.flush();
		}

		/**
		 * Override but do nothing, don't close System.out
		 * @see java.io.Writer#close()
		 */
		@Override
		public void close() throws IOException {
		}
	}
}
